/**
 * 询价.COM v1.0.0
 * http://xun-jia.com/
 *
 * Copyright (c) 2009 
 * 四川漾天空网络科技有限公司
 * 成都市天府软件园A3栋2楼
 *
 */
package com.xunjia.util;

import java.io.Serializable;
import java.net.URLEncoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Mark
 * 
 * @Email Mark_yang@xun-jia.com
 * 
 * @Date 2009-4-20 下午05:26:02
 * 
 */
public class CookieUtil implements Serializable {

	private static final long serialVersionUID = -5617282238013162103L;
	// COOKIE存活时间(单位:分钟)
	private static final byte ALIVE_TIME = 15;
	// 分钟换算秒数
	private static final byte SECONDS = 60;

	/**
	 * 添加COOKIE
	 * 
	 * @param request
	 * @param response
	 * @param name
	 * @param value
	 */
	public static void addCookie(HttpServletRequest request, HttpServletResponse response, String name, String value) {
		try {
			// 统一对value进行加密
			value = URLEncoder.encode(value, Constants.CHARACTER_UTF8);
			// 获取COOKIE
			Cookie[] cookies = request.getCookies();
			// 新建COOKIE
			Cookie original = null;
			// 遍历COOKIE
			for (Cookie cookie : cookies) {
				if (cookie.getName().equals(name)) {
					original = cookie;
					break;
				}
			}
			if (original == null) {
				original = new Cookie(name, value);
			} else {
				original.setValue(value);
			}
			// 设置过期时限
			original.setMaxAge(ALIVE_TIME * SECONDS);
			// 添加COOKIE
			response.addCookie(original);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取COOKIE值
	 * 
	 * @param request
	 * @param response
	 * @param name
	 * @return
	 */
	public static String getCookieValue(HttpServletRequest request, HttpServletResponse response, String name) {
		// 获取COOKIE
		Cookie[] cookies = request.getCookies();
		// COOKIE值
		String cookieValue = "";
		// 遍历COOKIE
		for (Cookie cookie : cookies) {
			if (cookie.getName().equals(name)) {
				cookieValue = cookie.getValue();
			}
		}
		return cookieValue;
	}

	/**
	 * 删除所有COOKIE
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	public static void deleteAllCookie(HttpServletRequest request, HttpServletResponse response) {
		// 获取COOKIE
		Cookie[] cookies = request.getCookies();
		// 遍历COOKIE
		for (Cookie cookie : cookies) {
			cookie.setMaxAge(0);
		}
	}

	/**
	 * 删除指定名称的COOKIE
	 * 
	 * @param request
	 * @param response
	 * @param cookieName
	 */
	public static void deleteCookieByName(HttpServletRequest request, HttpServletResponse response, String cookieName) {
		// 获取COOKIE
		Cookie[] cookies = request.getCookies();
		// 遍历COOKIE
		for (Cookie cookie : cookies) {
			if (cookie.getName().equals(cookieName)) {
				cookie.setMaxAge(0);
			}
		}
	}
}
